/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.guice.jpa;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.commons.lang.StringUtils;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.sapien.guice.Configuration;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

/**
 * Entity Manager Factory Provider.
 * @author Adam
 * @version $Id: EntityManagerFactoryProvider.java 29 2010-01-04 05:25:44Z a.ruggles $
 * 
 * Created on Oct 6, 2008 at 12:19:47 PM 
 */
@Singleton
public class EntityManagerFactoryProvider implements Provider<EntityManagerFactory> {
	/**
	 * Default Persistence Unit Name.
	 */
	public static final String DEFAULT_PERSISTENCE_UNIT = "DefaultPU";

	/**
	 * The Entity Manager Factory.
	 */
	private final EntityManagerFactory emFactory;

    /**
     * The JDBC Driver.
     */
	private static final String DB_DRIVER = "org.hsqldb.jdbcDriver";

	/**
	 * The in memory database url.
	 */
	private static final String DB_URL = "jdbc:hsqldb:mem:sapien";

	/**
	 * The database username.
	 */
	private static final String DB_USER = "sa";

	/**
	 * The database password.
	 */
	private static final String DB_PASSWORD = "";

    /**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private static final Logger LOG = LoggerFactory.getLogger(EntityManagerFactoryProvider.class);

	/**
	 * Constructs an Entity Manager Factory Provider.
	 * @param config The application Loader.
	 */
	@Inject
	public EntityManagerFactoryProvider(final Configuration config) {
		super();
		LOG.debug("Creating the entity manager factory");
		String unitName = config.getSetting(String.class, "config.jpa.persistenceUnit");
		if (StringUtils.isBlank(unitName)) {
			unitName = DEFAULT_PERSISTENCE_UNIT;
		}
		LOG.debug("Using unit name {}", unitName);
		emFactory = Persistence.createEntityManagerFactory(unitName, config.getAsProperties());
		seedDatabase();
	}

	/**
	 * Constructs an Entity Manager Factory Provider.
	 * @param persistenceUnit The name of the persistence unit.
	 * @param properties Additional properties to use when creating the factory.
	 */
	public EntityManagerFactoryProvider(final String persistenceUnit, final Map<String, Object> properties) {
		String unitName = persistenceUnit;
		if (StringUtils.isBlank(persistenceUnit)) {
			unitName = DEFAULT_PERSISTENCE_UNIT;
		}
		LOG.debug("Creating the entity manager factory");
		if (properties == null) {
			emFactory = Persistence.createEntityManagerFactory(unitName);
		} else {
			emFactory = Persistence.createEntityManagerFactory(unitName, properties);
		}
		seedDatabase();
	}

	/**
	 * {@inheritDoc}
	 * @see java.lang.Object#finalize()
	 */
	@Override
	protected void finalize() throws Throwable {
		if (emFactory != null && !emFactory.isOpen()) {
			emFactory.close();
		}
		super.finalize();
	}

	/**
	 * Returns an instance of the Entity Manager Factory.
	 * {@inheritDoc}
	 * @see kiff.util.Provider#get()
	 */
	public EntityManagerFactory get() {
		return emFactory;
	}

	/**
	 * Seeds the database from the DataSeed.xml file.
	 */
	private void seedDatabase() {
		final FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
		IDatabaseConnection connection = null;
		try {
			final IDataSet dataSet = builder.build(getClass().getResource("DataSeed.xml"));
			connection = new DatabaseConnection(getDatabaseConnection());
			connection.getConnection().createStatement().execute("SET REFERENTIAL_INTEGRITY FALSE;");
	        DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
	        connection.getConnection().createStatement().execute("SET REFERENTIAL_INTEGRITY TRUE;");
	    } catch (final DataSetException e) {
	    	LOG.error("Data Set Exception Occurred.", e);
		} catch (DatabaseUnitException e) {
			LOG.error("Database Unit Exception Occurred.", e);
		} catch (SQLException e) {
			LOG.error("SQL Exception Occurred.", e);
		} catch (ClassNotFoundException e) {
			LOG.error("ClassNotFoundException Exception Occurred.", e);
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					LOG.error("SQL Exception Occurred when attempting to close the connection.", e);
				}
			}
	    }
	}
	
	/**
	 * Returns a database connection.
	 * @return a database connection.
	 * @throws SQLException If a SQL exception occurs connecting to the database.
	 * @throws ClassNotFoundException If Database JDBC driver class is not found.
	 */
	private Connection getDatabaseConnection() throws SQLException, ClassNotFoundException	{
	    Class.forName(DB_DRIVER);
	    return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
	}
}
